package com.abc.robot01.activity

import android.os.Bundle
import android.util.Log
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.abc.robot01.R

import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.compose.ui.window.Popup
import com.abc.robot01.retrofit.bean.HousePlanDataDTO
import com.abc.robot01.vivemodel.HuXingShuJuViewModel2
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
import com.bumptech.glide.integration.compose.GlideImage

/**
 * 户型数据 通过电话号码查询进入
 */
class HuXingShuJuActivityByPhone : BaseVoiceActivity() {
    private val viewModel: HuXingShuJuViewModel2 by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
            viewModel.loadDataByPhone(intent.getStringExtra("phone")!!);
//            viewModel.loadDataByPhone("12555");
//            viewModel.loadDataByPhone("18098929436");
        setContent {
//            val showLeft = remember { viewModel.showLeft }
            val showDetailButton by remember { viewModel.showDetailButton }
            val selected2 by remember { viewModel.selected2 }
            var show by remember { viewModel.show }

            val selectedIndex by remember { viewModel.selectedIndex }

            MaterialTheme {
                Box {
                    Image(painter = painterResource(id = R.drawable.z1), contentDescription = "")
                    Column(modifier = Modifier.padding(start = 30.px, end = 30.px, top = 30.px)) {
//                        BackButton {
//                        }
                        Spacer(modifier = Modifier.height(30.px))
//                        Box(
//                            modifier = Modifier
//                                .size(570.px, 90.px)
//                                .background(
//                                    Color(0x00bac3db),
//                                ),
//                        ) {
//                            // 背景图片
//                            Box(
//                                modifier = Modifier
//                                    .size(570.px, 90.px)
//                                    .background(
//                                        Color.White.copy(alpha = 0.4f), shape = RoundedCornerShape(40.px,40.px,0.px,0.px)
//                                    ),
//                            )
////                            TopTabs()
//                        }
                        SystemFragmentBackground3(topStart = 40.px) {
                            Column(modifier = Modifier.padding(start = 30.px, end = 30.px)) {
                                Spacer(modifier = Modifier.height(30.px))
//                                if (showLeft.value) {
                                TAB1()
//                                }
                            }
                        }
                    }
                    BottomBar2(
                        cancelClicked = {
                            this@HuXingShuJuActivityByPhone.finish()
                        },
                        onDataClick = {
                            show = true
                        },
                        show = true,
                        selected1 = showDetailButton,
                        onClick = {
                            if(showDetailButton)
                            gotoNext()
                        })
                    if (show) {
                        MinimalDialog(url = viewModel.imageUrl, onConfirm = {
                            gotoNext()
                        }) {
                            show = false
                        }
                    }
                }
            }
        }
    }

    /**
     *  选择户型
     */
    @Composable
    fun TAB1() {
        val expanded1 = remember { viewModel.expanded1 }
        val selected1 = remember { viewModel.selected10 }

        val expanded2 = remember { viewModel.expanded2 }
        val selected2 = remember { viewModel.selected20 }

        Row(verticalAlignment = Alignment.CenterVertically) {
            BasicText(
                modifier = Modifier.offset(y = 0.dp),
                text = "户型数据名称",
                style = TextStyle(
                    fontWeight = FontWeight.Normal,
                    fontSize = 26.mysp,
                    color = MYBLACK,
                ),
            )
            Spacer(modifier = Modifier.width(20.px))
            val question = remember { viewModel.name }
            CustomStyledTextField2(
                text = question, textColor = MYBLACK_Percent5, size = DpSize(200.px, 50.px)
            )
            Spacer(modifier = Modifier.width(30.px))
            BasicText(
                modifier = Modifier.offset(y = 0.dp),
                text = "备注",
                style = TextStyle(
                    fontWeight = FontWeight.Normal,
                    fontSize = 26.mysp,
                    color = MYBLACK,
                ),
            )
            Spacer(modifier = Modifier.width(20.px))
            val remark = remember { viewModel.remark }
            CustomStyledTextField2(
                text = remark, textColor = MYBLACK_Percent5, size = DpSize(200.px, 50.px)
            )
//            Spacer(modifier = Modifier.width(30.px))
//            BasicText(
//                modifier = Modifier.offset(y = 0.dp),
//                text = "创建者",
//                style = TextStyle(
//                    fontWeight = FontWeight.Normal,
//                    fontSize = 26.mysp,
//                    color = MYBLACK,
//                ),
//            )

//            Spacer(modifier = Modifier.width(20.px))
//            Column {
//                CustomStyledTextField4(selected2, textColor = MYBLACK_Percent5) {
//                    expanded2.value = expanded2.value.not()
//                }
//                if (expanded2.value) {
//                    DropdownMenu2(expanded2, selected2, offsetY = (0).px)
//                }
//            }


            Spacer(modifier = Modifier.width(30.px))
            MyButton01(
                text = "查询", size = DpSize(148.px, 50.px), textColor = Color.White,
                containerColor = MYBLUE, shape = RoundedCornerShape(25)
            ) {
                viewModel.loadDataByPhone(intent.getStringExtra("phone")!!)
            }

            Spacer(modifier = Modifier.width(30.px))
            MyButton01(
                text = "重置",
                size = DpSize(148.px, 50.px),
                textColor = MYBLACK,
                containerColor = MYBLACK_Percent10,
                shape = RoundedCornerShape(25)
            ) {
                viewModel.reset()
            }
        }
        Spacer(modifier = Modifier.height(30.px))
        SimpleGrid()
    }

    @Composable
    fun DropdownMenu2(
        expanded: MutableState<Boolean>,
        selected: MutableState<String>,
        width: Dp = 374.px,
        offsetX: Dp = 0.px,
        offsetY: Dp = 0.px
    ) {
        val items: List<Pair<String, String>> by viewModel.designerList.collectAsState()
        Column(modifier = Modifier.background(Color.Blue)) {
            Popup(
                alignment = Alignment.TopStart,
                offset = IntOffset(0 * 30, 0),
                onDismissRequest = { expanded.value = false }) {
                Card(
                    modifier = Modifier
                        .width(width)
                        .offset(y = offsetY),
                    shape = RoundedCornerShape(bottomStart = 10.px, bottomEnd = 10.px),
                    colors = CardDefaults.cardColors(containerColor = Color.White),
                ) {
                    LazyColumn {
                        itemsIndexed(items, key = { index, item -> item.first }) { index, it ->
                            val isLastItem = index == items.lastIndex
                            Box(
                                modifier = Modifier
//                                    .background(
//                                        color = Color.Transparent,
//                                        shape = RoundedCornerShape(5.px))
                                    .fillMaxWidth()
                                    .height(80.px), // 修改为 dp 或者其他单位
                                contentAlignment = Alignment.CenterStart // 垂直和水平居中
                            ) {
                                BasicText(
                                    modifier = Modifier
                                        .clickable {
                                            expanded.value = false
                                            selected.value = it.second
                                            viewModel.selectedDesigner.value = it.first
                                        }
                                        .offset(x = 30.px),
                                    text = it.second,
                                    style = TextStyle(
                                        fontWeight = FontWeight.Normal,
                                        textAlign = TextAlign.Start,
                                        fontSize = 26.mysp,
                                        color = Color.Black,
                                    ),
                                )
                            }
                        }
                    }
                }
            }
        }
    }


    @Composable
    fun SimpleGrid(columns: Int = 7) {
        val items: List<HousePlanDataDTO> by viewModel.questionList.collectAsState()
        // Track the currently selected item index
        val selectedIndex = remember { viewModel.selectedIndex }
        LazyVerticalGrid(
            verticalArrangement = Arrangement.spacedBy(20.px), // 可以设置垂直间隔，例如16dp
            horizontalArrangement = Arrangement.spacedBy(20.px), // 水平间隔设置为 20px
            columns = GridCells.Fixed(columns), // 2 columns in the grid
            modifier = Modifier
                .fillMaxSize()
//                .height(592.px)
                .padding(start = 0.px, end = 0.px, top = 0.px, bottom = 84.px)
        ) {
            itemsIndexed(items, key = { index, item -> item.id + item.name }) { index, item ->
                Log.e(TAG, "thumbnail:" + item.imageUrl.toString())
                ImageTextCard(item, index, selectedIndex)
            }
        }
    }

    @OptIn(ExperimentalGlideComposeApi::class)
    @Composable
    fun ImageTextCard(item: HousePlanDataDTO, index: Int, selectedIndex: MutableState<Int>) {
        // Background color changes based on the selected state
        val backgroundColor =
            if (selectedIndex.value == index) MYBLUE.copy(alpha = 0.1f) else MYBLACK_Percent5
        Box(
            modifier = Modifier
                .clickable(
                    interactionSource = remember { MutableInteractionSource() },
                    indication = null,
                    onClick = { // Removes ripple effect))
                        selectedIndex.value = index
//                        viewModel.selected1.value = item.renderCount > 0
                        viewModel.name1.value = item.name
                        if (viewModel.name1.value.trim() == "" || viewModel.name1.value == "null") {
                            viewModel.name1.value = "/"
                        }
                        viewModel.showDetailButton.value = true
                        viewModel.imageUrl = item.imageUrl
                        viewModel.housePlanDataId = item.id
                        viewModel.remark1.value = item.remarks!!
                        viewModel.remark1.value = viewModel.remark1.value.replace("null", "/")
                        viewModel.type.value = viewModel.immutableMap[item.type.toInt()] ?: "/"
                        viewModel.createTime.value = item.createTime
                        viewModel.customerName.value = item.customerName
                        viewModel.customerPhone.value = item.customerPhone
                    })
                .background(color = backgroundColor, shape = RoundedCornerShape(14.px))
                .width(240.px)
                .height(327.px)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(0.px),
                horizontalAlignment = Alignment.Start
            ) {
                Card(
                    colors = androidx.compose.material3.CardDefaults.cardColors(
                        containerColor = MYBLACK_Percent10 // 设置背景色为红色
                    ),
                    shape = RoundedCornerShape(10.px),
                    modifier = Modifier
                        .background(Color.Transparent)
                        .width(240.px)
                        .height(240.px)
                ) {
                    GlideImage(
                        contentScale = ContentScale.Fit,
                        model = item.imageUrl,
                        contentDescription = "",
                        modifier = Modifier.fillMaxSize()
                    )
                }
                Spacer(modifier = Modifier.height(10.px))
                BasicText(
                    modifier = Modifier.offset(x = 20.px),
                    maxLines = 1,
                    overflow = TextOverflow.Clip,
                    text = item.name,
                    style = TextStyle(
                        fontSize = (24 / 3.5f).sp,
                        color = Color.Black,
                        lineHeight = (24 / 3.5f).sp
                    )
                )
                Spacer(modifier = Modifier.height(5.px))

                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(
                            start = 20.px, end = 20.px
                        )
                ) {
                    BasicText(
                        maxLines = 1,
                        overflow = TextOverflow.Clip,
                        text = "" + if(item.remarks==null || item.remarks.trim()== "null")"/" else item.remarks ,
                        style = TextStyle(
                            fontSize = (20 / 3.5f).sp,
                            color = MYBLACK_Percent60,
                            lineHeight = (24 / 3.5f).sp
                        )
                    )
//                    Spacer(modifier = Modifier.weight(14f))
//                    BasicText(
//                        maxLines = 1,
//                        overflow = TextOverflow.Clip,
//                        text = "" + item.innerArea + "㎡",
//                        style = TextStyle(
//                            fontSize = (20 / 3.5f).sp,
//                            color = MYBLACK_Percent60,
//                            lineHeight = (24 / 3.5f).sp
//                        )
//                    )
                }
            }
            Image(
                modifier = Modifier.offset(x = 189.px, y = 40.px),
                painter = painterResource(id = if (selectedIndex.value == index) R.drawable.s13 else R.drawable.s12), // 替换为你的图片资源ID
                contentDescription = null,
                contentScale = ContentScale.Crop, // 使图片填充整个背景
            )
        }
    }

    override fun onResume() {
        super.onResume()
        viewModel.reset()
    }

//    @Composable
//    fun BoxScope.TopTabs(){
//        val showLeft = remember { viewModel.showLeft }
//        val showRight = remember { viewModel.showRight }
//        val showCenter = remember { viewModel.showCenter }
//
//        if (showLeft.value) {
//            Image(
//                modifier = Modifier.align(Alignment.TopStart),
//                painter = painterResource(id = R.drawable.tab_left), // 替换为你的图片资源ID
//                contentDescription = null,
//                contentScale = ContentScale.Crop, // 使图片填充整个背景
//            )
//        }
//
//        if (showCenter.value) {
//            Image(
//                modifier = Modifier.align(Alignment.Center),
//                painter = painterResource(id = R.drawable.tab_center), // 替换为你的图片资源ID
//                contentDescription = null,
//                contentScale = ContentScale.Crop, // 使图片填充整个背景
//            )
//        }
//
//        if (showRight.value) {
//            Image(
//                modifier = Modifier.align(Alignment.BottomEnd),
//                painter = painterResource(id = R.drawable.tab_right), // 替换为你的图片资源ID
//                contentDescription = null,
//                contentScale = ContentScale.Crop, // 使图片填充整个背景
//            )
//        }
//
//        Row(
//            modifier = Modifier
//                .fillMaxSize()
//                .padding(start = 50.px)
//                .offset(0.dp, 0.dp),
//            horizontalArrangement = Arrangement.spacedBy(
//                55.px
//            ),
//            verticalAlignment = Alignment.CenterVertically
//        ) {
//            BasicText(
//                text = "选择户型",
//                style = TextStyle(
//                    fontWeight = FontWeight.Bold,
//                    fontSize = size,
//                    color = if (showLeft.value) MYBLACK else MYBLACK_Percent60,
//                ),
//                modifier = Modifier
//                    .clickable(
//                        indication = null,  // Removes the ripple effect
//                        interactionSource = remember { MutableInteractionSource() }  // Keeps track of interactions
//                    ) {
//                        showLeft.value = true;
//                        showCenter.value = false
//                        showRight.value = false;
//                    }
//            )
//            BasicText(
//                text = "导入户型",
//                style = TextStyle(
//                    fontWeight = FontWeight.Bold,
//                    fontSize = size,
//                    color = if (showCenter.value) MYBLACK else MYBLACK_Percent60,
//                ),
//                modifier = Modifier
//                    .clickable(
//                        indication = null,  // Removes the ripple effect
//                        interactionSource = remember { MutableInteractionSource() }) {
//                        showLeft.value = false;
//                        showCenter.value = true
//                        showRight.value = false;
//
//                    }
//            )
//            BasicText(
//                text = "绘制户型",
//                style = TextStyle(
//                    fontWeight = FontWeight.Bold,
//                    fontSize = size,
//                    color = if (showRight.value) MYBLACK else MYBLACK_Percent60,
//                ),
//                modifier = Modifier
//                    .clickable(
//                        indication = null,  // Removes the ripple effect
//                        interactionSource = remember { MutableInteractionSource() }) {
//                        showLeft.value = false;
//                        showCenter.value = false
//                        showRight.value = true;
//                    }
//            )
//        }
//
//    }


    private fun gotoNext() {
        startActivity<HuXingTiaoZheng> {
            putExtra("housePlansDataId", viewModel.housePlanDataId)
            putExtra("name", "name is null")
            Log.e(
                TAG,
                "designPackageId:" + intent.getStringExtra("designPackageId")
            )
            putExtra(
                "designPackageId",
                intent.getStringExtra("designPackageId")
            )
            putExtra("housePlansId", viewModel.housePlanId)
        }
    }

    companion object {
        val TAG = "户型数据"
    }

    @OptIn(ExperimentalGlideComposeApi::class)
    @Composable
    fun MinimalDialog(url: String, onConfirm: () -> Unit, onDismissRequest: () -> Unit) {
        Dialog(
            properties = DialogProperties(
                usePlatformDefaultWidth = false,
                dismissOnBackPress = false, // 禁用返回按钮
                dismissOnClickOutside = false // 禁用点击外部关闭对话框
            ),
            onDismissRequest = { onDismissRequest() }) {
            Box(
                modifier = Modifier
                    .background(color = Color.White, shape = RoundedCornerShape(40.px))
                    .size(1364.px, 860.px)
                    .padding(30.px),
            ) {

                Row {
                    Box(
                        modifier = Modifier
                            .size(800.px, 800.px)
                            .padding(30.px)
                            .background(
                                color = Color(0xffd9d9d9),
                                shape = RoundedCornerShape(30.px)
                            ),
                    ) {
                        Box(
                            modifier = Modifier
                                .size(740.px) // Set the viewport size to 200x200
                                .background(Color.Transparent) // Optional background for the frame
//                .horizontalScroll(horizontalScrollState) // Enable horizontal scrolling
//                .verticalScroll(verticalScrollState) // Enable vertical scrolling
                        ) {
                            GlideImage(
                                model = url,
                                contentDescription = "Image",
                                modifier = Modifier
                                    .background(Color.Transparent)
                                    .fillMaxSize()
                                    .clickable {
                                        // 点击事件
                                    },
                                contentScale = ContentScale.Fit // 或者使用其他的内容缩放策略，如 Fit、FillBounds 等
                            )
                        }
                    }
                    Left()
                }

                com.abc.robot01.activity.MyButton01(
                    modifier = Modifier.align(Alignment.BottomEnd),
                    text = "应用", size = DpSize(144.px, 34.px), textColor = Color.White,
                    containerColor = MYBLUE, shape = RoundedCornerShape(6.px)
                ) {
                    onConfirm()
                }
                Image(
                    modifier = Modifier
                        .align(Alignment.TopEnd)
                        .clickable {
                            onDismissRequest()
                        },
                    painter = painterResource(R.drawable.close2),
                    contentDescription = ""
                )
            }
        }
    }

    @Composable
    fun Left() {
        val name by remember { viewModel.name1 }
        val customerName by remember { viewModel.customerName }
        val customerPhone by remember { viewModel.customerPhone }
        val type by remember { viewModel.type }
        val createTime by remember { viewModel.createTime }
        val remark1 by remember { viewModel.remark1 }

        Log.e(TAG, "Left");


        Column(modifier = Modifier.padding(top = 30.px)) {
            BasicText(
                modifier = Modifier.offset(x = 28.px),
                text = name,
                style = TextStyle(
                    fontWeight = FontWeight.Normal,
                    fontSize = 26.mysp,
                    color = MYBLACK,
                ),
            )
            Spacer(modifier = Modifier.height(36.px))
            Column(modifier = Modifier.padding(start = 46.px)) {
                BasicText(
                    text = "数据类型: ${type}",
                    style = TextStyle(
                        fontWeight = FontWeight.Normal,
                        fontSize = 24.mysp,
                        color = Color.Black.copy(alpha = 0.6f),
                    ),
                )

                Spacer(modifier = Modifier.height(30.px))
                BasicText(
                    text = "生成时间：${createTime}",
                    style = TextStyle(
                        fontWeight = FontWeight.Normal,
                        fontSize = 24.mysp,
                        color = Color.Black.copy(alpha = 0.6f),
                    ),
                )
                Spacer(modifier = Modifier.height(30.px))
                BasicText(
                    text = "备注：${remark1}",
                    style = TextStyle(
                        fontWeight = FontWeight.Normal,
                        fontSize = 24.mysp,
                        color = Color.Black.copy(alpha = 0.6f),
                    ),
                )
                Spacer(modifier = Modifier.height(30.px))
                Spacer(
                    modifier = Modifier
                        .height(4.px)
                        .width(380.px)
                        .background(Color.Black.copy(alpha = 0.80f))
                )
                Spacer(modifier = Modifier.height(30.px))
                BasicText(
                    text = "客户名称：${customerName}",
                    style = TextStyle(
                        fontWeight = FontWeight.Normal,
                        fontSize = 24.mysp,
                        color = Color.Black.copy(alpha = 0.6f),
                    ),
                )
                Spacer(modifier = Modifier.height(30.px))
                BasicText(
                    text = "客户手机：${customerPhone}",
                    style = TextStyle(
                        fontWeight = FontWeight.Normal,
                        fontSize = 24.mysp,
                        color = Color.Black.copy(alpha = 0.6f),
                    ),
                )
            }
        }
    }
}

